<template>
  <div class="app-container">
    <div class="bg-container">
      <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="form">
        <el-form-item label="主机名称" prop="name">
          <el-input
              v-model="form.name"
              clearable
              placeholder="请输入主机名称"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机IP地址" prop="ipAddress">
          <el-input
              v-model="form.ipAddress"
              clearable
              placeholder="请输入主机IP地址"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机的注意事项" prop="remarks">
          <el-input
              v-model="form.remarks"
              clearable
              placeholder="请输入主机的注意事项"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机用户名" prop="username">
          <el-input
              v-model="form.username"
              clearable
              placeholder="请输入主机用户名"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机密码" prop="password">
          <el-input
              v-model="form.password"
              clearable
              placeholder="请输入主机密码"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              v-model="form.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              icon="Plus"
              plain
              type="primary"
              @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              :disabled="multiple"
              icon="Delete"
              plain
              type="danger"
              @click="handleDeleteList"
          >删除
          </el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
              icon="Download"
              plain
              type="warning"
              @click="handleExport"
          >导出
          </el-button>
        </el-col> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="computerList" :show-overflow-tooltip="true" :stripe="true"
                @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column label="主机的id" prop="id"/>
        <el-table-column label="主机名称" prop="name"/>
        <el-table-column label="操作系统" prop="opsType"/>
        <el-table-column label="主机IP地址" width="120px" prop="ipAddress"/>
        <el-table-column label="主机的注意事项" width="200px" prop="remarks"/>
        <el-table-column label="主机用户名" width="120px" prop="username"/>
        <el-table-column label="主机密码" prop="password"/>
        <el-table-column
            align="center"
            label="创建时间"
            prop="createTime"
            width="180px"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作"
                         width="240px">
          <template #default="scope">
            <el-button circle icon="Edit" plain type="primary"
                       @click="handleUpdate(scope.row)">
            </el-button>
            <el-button circle icon="Delete" plain type="danger"
                       @click="handleDelete(scope.row)">
            </el-button>
            <el-button circle plain type="success"
                       @click="handleInstallFilebeat(scope.row)">F</el-button>
            <el-button circle plain type="info"
                       @click="handleOpenWebshell(scope.row)">W</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[3, 5, 7, 10]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; justify-content: flex-end"
          @size-change="getList"
          @current-change="getList"
      />
    </div>

    <!-- 添加或修改主机 -->
    <el-dialog v-model="open" :title="title" append-to-body width="600px">
      <el-form ref="computerRef" :model="addForm" :rules="rules" label-width="120px">
        <el-form-item label="主机名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入主机名称"/>
        </el-form-item>
        <el-form-item label="操作系统" prop="opsType">
          <el-select v-model="addForm.opsType" placeholder="请选择操作系统">
            <el-option v-for="item in optsList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机IP地址" prop="ipAddress">
          <el-input v-model="addForm.ipAddress" placeholder="请输入主机IP地址"/>
        </el-form-item>
        <el-form-item label="主机的注意事项" prop="remarks">
          <el-input v-model="addForm.remarks" placeholder="请输入主机的注意事项"/>
        </el-form-item>
        <el-form-item label="主机用户名" prop="username">
          <template #description>
            
          </template>
          <el-input v-model="addForm.username" placeholder="请输入主机用户名"/>
        </el-form-item>
        <div style="color: red;margin-top: -15px;margin-left: 20px; font-size: 12px;">该用户必须具有sudo权限</div>
        <el-form-item label="主机密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入主机密码"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <m-web-shell ref="mWebShellA"></m-web-shell>

  </div>
</template>

<script name="DeployHost" setup>

import mWebShell from "./components/webShell.vue";
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {
  addComputer,
  delComputer,
  delComputerList,
  exportComputer,
  getComputer,
  listComputer,
  updateComputer,
  getAllOs,
  installFilebeat
} from "@/api/computer";
import {parseTime} from "@/utils/utils";
import { ro } from "element-plus/es/locales.mjs";

const {proxy} = getCurrentInstance();

const computerList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const form = reactive({
  id: null,
  name: null,
  ipAddress: null,
  remarks: null,
  username: null,
  password: null,
  createTime: null,
})

const optsList = ref([]); // 操作系统列表
const addForm = reactive({
  id: null,
  name: null,
  ipAddress: null,
  remarks: null,
  username: null,
  password: null,
  opsType: null,
})

const rules = {
  name: [
    { required: true, message: '请输入主机名称', trigger: 'blur' },
  ],
  ipAddress: [
    { required: true, message: '请输入主机IP地址', trigger: 'blur' },
  ],
  remarks: [
    { required: true, message: '请输入主机的注意事项', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入主机用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入主机密码', trigger: 'blur' },
  ],
  opsType: [
    { required: true, message: '请选择操作系统', trigger: 'change' },
  ],
}

const data = reactive({
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    total: 0,
  },
});

const {queryParams} = toRefs(data);

// 获取列表数据
function getList() {
  loading.value = true;
  const { name, ipAddress, remarks, username, password, createTime } = form;
  const params = {
    name,
    ipAddress,
    remarks,
    username,
    password,
    createTime,
    pageNo: queryParams.value.pageNo,
    pageSize: queryParams.value.pageSize,
  }
  listComputer(params).then(response => {
    computerList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 安装filebeat
const handleInstallFilebeat = (row) => {
  installFilebeat(row.id).then(response => {
    proxy.$modal.msgSuccess("安装成功");
  })
}

// 打开webshell
const handleOpenWebshell = (row) => {
  proxy.$refs.mWebShellA.openDialog(row.ipAddress, row.username, row.password);
  console.log(row);
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 获取所有操作系统
const bindGetAllOs = () => {
  getAllOs().then(response => {
    optsList.value = response.data;
  });
}

// 表单重置
function reset() {
  // 重置验证规则
  proxy.resetForm("computerRef");
  proxy.resetForm("queryRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  for (const key in addForm) {
    delete addForm[key];
  }
  proxy.resetForm("computerRef");
  open.value = true;
  title.value = "添加主机";
}

// 修改按钮操作
function handleUpdate(row) {
  addForm.id = row.id;
  addForm.name = row.name;
  addForm.ipAddress = row.ipAddress;
  addForm.remarks = row.remarks;
  addForm.username = row.username;
  addForm.password = row.password;
  addForm.opsType = row.opsType;
  open.value = true;
  title.value = "修改主机";
}

// 提交按钮
function submitForm() {
  proxy.$refs["computerRef"].validate(valid => {
    if (valid) {
      if (addForm.id) {
        updateComputer(addForm).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addComputer(addForm).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除主机"' + row.id + '"的数据项？').then(function () {
    return delComputer({id: row.id});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 批量删除按钮操作
function handleDeleteList() {
  const idList = ids.value;
  proxy.$modal.confirm('是否确认删除主机"' + idList + '"的数据项？').then(function () {
    return delComputerList({ids: idList.join(',')});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  exportComputer(queryParams.value)
}

onMounted(async () => {
  await bindGetAllOs();
  await getList();
});
</script>